from flask import Flask, session, redirect, url_for, escape, request

'''
会话，允许在不同的请求之间存储信息
'''
app = Flask(__name__)

# 加密，用户没有密钥的时候只允许查看，不允许修改
app.secret_key = b'\xa8yVs0\x8e\xe6\x03\x9fFp\x1d\xd9\xda\xb3\x00'

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])  # escape 用来转义
    return 'You are not logged in'


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="POST">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == "__main__":
    app.run()